<template xmlns="">
  <div :style="{
    width: imageFrameWidth + 'vw',
    height: imageFrameHeight + 'vw',
  }" class="image-frame">
    <div :style="{
      width: imageWidth + 'vw',
      height: imageHeight + 'vw',
    }" class="image-content">
      <Image :src="src" :preview="preview" class="auto-crop" :style="imageStyle">
        <template #previewMask>
          <ZoomInOutlined  class="ZoomInOutlined-png"/>
        </template>
      </Image>
    </div>
  </div>
</template>

<script setup>
import { defineProps, ref, computed, watch, onMounted } from 'vue';
import { Image } from 'ant-design-vue';
import { ZoomInOutlined } from '@ant-design/icons-vue'

const props = defineProps({
  src: {
    default: '',
    type: String
  },
  width: {
    default: 20,
    type: Number
  },
  height: {
    default: 20,
    type: Number
  },
  preview: {
    default: false,
    type: Boolean
  }
})
const imageFrameWidth = ref(0)
const imageFrameHeight = ref(0)
const imageWidth = ref(0);
const imageHeight = ref(0);
const img_w = ref(null);
const img_h = ref(null);

// 动态计算图片样式
const imageStyle = computed(() => ({
  width: imageWidth.value + 'vw', // 宽度切换
  height: imageHeight.value + 'vw', // 高度自适应
  transition: 'all 0.5s ease', // 添加平滑过渡效果
}));

const getImageW_H = () => {
  imageFrameWidth.value = props.width / 1920 * 100
  imageFrameHeight.value = props.height / 1920 * 100
  if (props.width / img_w.value > props.height / img_h.value) {
    imageWidth.value = imageFrameWidth.value
    imageHeight.value = (img_h.value / img_w.value * imageFrameWidth.value)
  } else {
    imageHeight.value = imageFrameHeight.value
    imageWidth.value = ((img_w.value / img_h.value) * imageHeight.value)
  }
}

const getImageInfo = () => {
  if (!img_w.value) {
    const imgEl = document.createElement('img')
    imgEl.src = props.src
    imgEl.onload = (e) => {
      img_w.value = imgEl.width
      img_h.value = imgEl.height
      getImageW_H()
    }
  } else {
    getImageW_H()
  }
};

onMounted(() => {
  getImageInfo()
})

// 监听 props 的变化
watch(
  () => props.width, // 监听的源
  (newValue, oldValue) => {
    getImageInfo()
  }
);
</script>

<style lang="less" scoped>
.image-frame {
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  position: relative;
  transition: all 0.5s;
  cursor: pointer;

  .image-content {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    transition: all 0.5s;

    .ZoomInOutlined-png{
      font-size: 1vw;
    }
  }
}
</style>
